package org.zjt.gc;

import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import sun.misc.Cleaner;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-06-01 下午2:48
 * @see Cleaner
 *
 * Cleaner 使用：
 *
 *      1、Cleaner 中注册对象。注册一个对象O 、回收对象的 Runnable 线程。返回一个该对象返回回收句柄。
 *
 *      2、调用该回收句柄，回收对象。
 *
 */
public class CleanerTest {

    public static void main(String[] args) {
        try (Room myRoom = new Room(7, User.builder().addr("xian").name("zhangsan").build())) {
            System.gc();
            System.out.println("Goodbye");
        }
    }
}


 class Room implements AutoCloseable {

     private final State state;

     private final Cleaner cleaner;

     private User user ;


     /**
      *
      * Resource that requires cleaning. Must not refer to Room!
      */
    private class State implements Runnable {
        int numJunkPiles;

        State(int numJunkPiles) {
            this.numJunkPiles = numJunkPiles;
        }

        // Invoked by close method or cleaner
        @Override
        public void run() {
            System.out.println("Cleaning room" + Room.this.user);
            numJunkPiles = 0;
        }
    }


    public Room(int numJunkPiles,User user ) {
        state = new State(numJunkPiles);
        this.user = user;
        this.cleaner = Cleaner.create(this, state);
    }

    @Override
    public void close() {

        // 使用cleaner句柄回收该Rom引用。
        cleaner.clean();
    }
}

@Getter
@Builder
class User{
    private String name;
    private String addr;
}